﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoKnow.CloudEdu.CMS.Host.Models;
using DoKnow.CloudEdu.Common.Consts;
using DoKnow.CloudEdu.DataContract.Model.Base;
using DoKnow.Common.Utility;
using Newtonsoft.Json;
using System.Web.Optimization;
using Newtonsoft.Json.Converters;
namespace DoKnow.CloudEdu.CMS.Host.Controllers
{
    public class BsModuleController : BaseController
    {
        //
        // GET: /BsModule/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获所有模块树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetBsModuleJsTree()
        {
            try
            {
                var bsModuleList = BuildBsModuleJsTree();
                var result = Json(bsModuleList);
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据ID获取模块
        /// </summary>
        /// <returns></returns>
        public string GetBsModuleById(string id)
        {
            try
            {
                BSModuleInfo bsModule = CurCache.BSModuleFull.Find(i => i.ID == int.Parse(id));
                string resultStr = JsonConvert.SerializeObject(bsModule, new JsonSerializerSettings() { DateFormatHandling =Newtonsoft.Json.DateFormatHandling.IsoDateFormat});
                return resultStr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private List<JsTreeNode> BuildBsModuleJsTree()
        {
            return CurCache.BSModuleFull.OrderBy(o => o.ParentID).ThenBy(o => o.ModuleOrder).Select(
               n => new JsTreeNode
               {
                   icon = n.ModuleIcon,
                   id = n.ID.ToString(),
                   parent = (n.ParentID == null || n.ParentID == 0) ? "#" : n.ParentID.ToString(),
                   text = n.ModuleName,
                   state = new State
                   {
                       opened = true,
                       disabled = false,
                   }
               }
               ).ToList();
        }

        /// <summary>
        /// 保存模块
        /// </summary>
        /// <param name="clickKey"></param>
        /// <param name="name"></param>
        /// <param name="parentId"></param>
        /// <param name="viewUrl"></param>
        /// <returns></returns> 
        public ActionResult SetBsModule(string id, string code, string name, string parentId, string remark, string createUser, string createDate, string url, string order, string icon)
        {
            try
            {
                BSModuleInfo bsModuleInfo = new BSModuleInfo();
                bsModuleInfo.ModuleCode = code;
                bsModuleInfo.ModuleName = name;
                if (!string.IsNullOrEmpty(parentId))
                    bsModuleInfo.ParentID = int.Parse(parentId);
                else
                    bsModuleInfo.ParentID = 0;
                bsModuleInfo.Remark = remark;
                bsModuleInfo.Modifier = CurrentUser.UserEntity.RealName;
                bsModuleInfo.ModifyTime = System.DateTime.Now;
                bsModuleInfo.ModuleUrl = url;
                bsModuleInfo.ModuleOrder = int.Parse(order == "" ? "0" : order);
                bsModuleInfo.ModuleIcon = icon;
                //var bsModuleClient = new BsModuleManagerClient();

                if (!string.IsNullOrEmpty(id))
                {
                    bsModuleInfo.ID = int.Parse(id);
                    bsModuleInfo.Creator = createUser;
                    bsModuleInfo.CreateTime = Convert.ToDateTime(createDate);

                    //var result = bsModuleClient.Update(bsModuleInfo);
                    var wrap = HttpHelper.Post(Server + ServicePath.ModuleWrite,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "UpdateBSModule", 
                      Pars = 
                      new {
                          Module = bsModuleInfo 
                          } 
                    },new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
                    if (wrap.IsSuccess)
                    {
                        //更新moduleInfo的缓存信息
                        CacheHelper.Remove<ModuleDatas>(CacheKey.BSModuleFull);
                    }
                    //AddOperationLog(
                    //     MB.Stylist.BaseSystem.Model.BusinessTarget.Module,
                    //     MB.Stylist.BaseSystem.Model.BusinessAction.Edit,
                    //     bsModuleInfo.ID,
                    //     string.Format("用户[{0}]更新模块Code={1}", UserSession.Current.UserCode, bsModuleInfo.ModuleCode));

                    return Json(wrap);
                }
                else
                {
                    bsModuleInfo.Creator = CurrentUser.UserEntity.RealName;
                    bsModuleInfo.CreateTime = System.DateTime.Now;
                    var wrap = HttpHelper.Post(Server + ServicePath.ModuleWrite,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "CreateBSModule",
                    Pars =
                    new
                    {
                        Module = bsModuleInfo
                    }
                }, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
                    if (wrap.IsSuccess)
                    {
                        //更新moduleInfo的缓存信息
                        CacheHelper.Remove<ModuleDatas>(CacheKey.BSModuleFull);
                    }
                    //temp code
                    //BSRoleModuleInfo roleModule = new BSRoleModuleInfo()
                    //{
                    //    ModuleID = result.Data[0].ID,
                    //    RoleID = CurrentUser.UserRoles[0].RoleID
                    //};
                    //Invoke<BSRoleModuleAddDto, BSRoleModuleAddResponse>(ApiNameConst.BSRoleModuleAdd, roleModule);
                    //CacheHelper.Remove<List<BSRoleModuleFilterDto>>(LocalCacheKeyConst.BSRoleModuleFull);

                    return Json(wrap);
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 删除模块和子模块
        /// </summary>
        /// <param name="ModuleId"></param>
        /// <returns></returns>
        public string DeleteBsModule(string id)
        {
            try
            {
                //var bsModuleClient = new BsModuleManagerClient();
                //bool re = bsModuleClient.DeleteItemAndChildrenById(int.Parse(id)).DataContext;
                var re = HttpHelper.Post(Server + ServicePath.ModuleWrite,
                JsonConvert.SerializeObject(
                new
                {
                    ActionName = "DeleteBSModule",
                    Pars =
                    new
                    {
                        Id = id
                    }
                }));
                if (re.IsSuccess)
                {
                    //更新moduleInfo的缓存信息
                    CacheHelper.Remove<ModuleDatas>(CacheKey.BSModuleFull);
                    //CacheHelper.Remove<List<BSRoleModuleFilterDto>>(LocalCacheKeyConst.BSRoleModuleFull);
                    return "OK";
                }
                else
                {
                    return "ERROR";
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
